package com.credithc.customers.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.customers.api.service.ICustomerUnifyService;
import com.credithc.customers.api.utils.RequestUtils;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.ro.BaseRequest;
import com.credithc.customers.base.ro.CustomerUnifyLoginRo;
import com.credithc.framework.log.annotation.Trace;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Title: 统一登录相关接口
 * @Author: fby
 * @Date: 2020/2/27 15:43
 * @Description: com.credithc.customers.api.controller
 * @Version: V1.0.0
 */
@RestController
@RequestMapping("/api/yzt/v2/unify")
@Slf4j
@Trace
public class CustomerUnificationController {
    @Autowired
    MessageFactory messageFactory;
    @Autowired
    ICustomerUnifyService customerUnifyService;
    @Autowired
    RequestUtils requestUtils;
    /**
     * @description: 统一登录接口
     * @author: fby
     * @date: 2020/02/27 16:37
     * @param: request
     * @return: com.credithc.baseserv.core.message.Message
     */
    @PostMapping("/login")
    public Message login(HttpServletRequest request) {
        try {
            String requestStr = RequestUtils.generateRequest(request);
            BaseRequest<CustomerUnifyLoginRo> bRequest = JSON.parseObject(requestStr, new TypeReference<BaseRequest<CustomerUnifyLoginRo>>() {
            });
            Map<String, Object> map = customerUnifyService.unifyLogin(bRequest);
            if (map.get("msg") != null) {
                return messageFactory.getInstance(Integer.parseInt(map.get("code").toString()), map.get("msg").toString(), map.get("resMap"));
            }
            return messageFactory.getInstance(CoreCodes.CORE_SUCCESS, "登录成功", map.get("resMap"));
        } catch (IOException e) {
            throw new CustomerException(CustomerCodes.READ_REQUEST_ERROR);
        } catch (JSONException e) {
            log.info("登录接口参数格式错误，异常信息：{}", e.getMessage());
            throw new CustomerException(CustomerCodes.FAST_JSON_ERROR);
        }
    }

}
